const PSD = require('psd');
const fs = require('fs-extra');
let fileName = "平台-地域分析";
const psd = PSD.fromFile(`./psd/${fileName}.psd`);
const api = require('./api.js');
psd.parse();


class HtmlFactory {
    constructor(psd, outputPath) {
        let nodes2 = api.getVisibleNodes(psd);//这种方式获取的node，是精简版本，
        let nodes3 = api.getDetailVisibleNodes(psd);//这种方式获取的node，是详细，
        let structure = api.getStructure(psd);//这种方式获取的node，是精简版本，

        let nodes = api.getLayerNodes(psd);//这种方式获取的，包含详细信息


        this.psd = psd;
        this.outputPath = outputPath;
        this.nodes = nodes3;
        this.result = {
            html: [],
            css: [],
        };

        fs.outputFileSync(`${this.outputPath}/structure.json`, JSON.stringify(structure, null, '    '));

    }

    generateCss(node, index) {
        let html = this.result.html;
        let css = this.result.css;
        let style;
        let left = node.layer.left;
        let top = node.layer.top;
        let width = node.layer.width;
        let height = node.layer.height;
        let name = node.layer.name;
        let text = "";
        let img = `./images/${index}_${node.layer.name}.png`;
        let opacity = node.layer.opacity / 255;


        if (node.name === '圆角矩形 37x') {
            debugger;
        }

        if (index === 94) {
            debugger;
        }

        if (node.layer.typeTool) {//文本
            // console.log(node.layer.typeTool().export())//输出文本样式
            style = node.layer.typeTool().export();
            text = style.value;
        }

        try {
            // console.log(index + '***' + node.layer.image.length + '***' + name);
        } catch (e) {
            // console.log(e)
            return new Promise((resolve) => { resolve(); });
        }


        let textFont = '';
        if (style) {
            textFont = `
          font-family:"${style.font.name}";
          color:rgba(${style.font.colors[0].join(',')});
          font-size:${style.font.sizes[0]}px;
        `;
        } else {
            textFont = `
        text-indent:-99999px;
        background:url("./images/${index}.png");`;
        }

        this.result.css.push(`.c_${css.length}{
            opacity:${opacity};
          position:absolute;
          left:${left}px;
          top:${top}px;
          width:${width}px;
          ${textFont}
          height:${height}px;
        }`);
        this.result.html.push(`<div class="c_${html.length}">${text || name}</div>`);
        console.log(index + '***' + node.layer.image.length + '***' + name);


        return node.layer.image.saveAsPng(`${this.outputPath}/images/${index}.png`);

    }

    runNodes() {
        let index = 0;
        let that = this;
        const run = (callback) => {
            if (index >= that.nodes.length) {

                // console.log(css.join('\r\n'));
                // console.log(html.reverse().join('\r\n'));


                fs.outputFileSync(`${that.outputPath}/css.css`, that.result.css.join('\r\n'));
                fs.outputFileSync(`${that.outputPath}/index.html`, `<html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <meta http-equiv="X-UA-Compatible" content="ie=edge">
            <title>Document</title>
            <link rel="stylesheet" href="./css.css" />
        </head>
        <body>
                ${that.result.html.reverse().join('\r\n')}
        
        </body>
        </html>
                    `);

                callback();
                return;
            }

            that.generateCss(that.nodes[index], index++).then(() => {
                run(callback);
            });
        };

        return new Promise((resolve) => { run(resolve); });
    }

    generate() {
        return new Promise((resolve) => {
            return this.runNodes().then((data) => {
                resolve(data);
            });
        });
    }
}

const getHtmlData = (function toHTML(psd, outputPath) {

    return function _getHtmlData(psd, outputPath) {
        debugger;
        fs.ensureDirSync(outputPath + "/images");
        fs.emptyDirSync(outputPath + "/images");
        return new HtmlFactory(psd, outputPath).generate();
    };

}());


module.exports = {
    getHtmlData
};


// getHtmlData(psd, `./dist/${fileName}/`);
